package cn.powerone.scm.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import cn.powerone.common.utils.DateUtils;
import cn.powerone.scm.domain.*;
import cn.powerone.scm.mapper.ScmCustomerOrderItemsMapper;
import cn.powerone.scm.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import cn.powerone.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import cn.powerone.scm.mapper.ScmCustomerOrdersMapper;

/**
 * 客户订单Service业务层处理
 * 
 * @author PowerOne
 * @date 2025-07-04
 */
@Service
public class ScmCustomerOrdersServiceImpl implements IScmCustomerOrdersService 
{
    @Autowired
    private ScmCustomerOrdersMapper scmCustomerOrdersMapper;

    @Autowired
    private IScmCustomerQuotesService scmCustomerQuotesService;

    @Autowired
    private IScmProjectsService scmProjectsService;
    @Autowired
    private IScmCustomerService scmCustomerService;
    @Autowired
    private IScmMyCompanyInfoService scmMyCompanyInfoService;

    @Autowired
    private IScmSequenceParmService scmSequenceParmService;

    @Autowired
    private ScmCustomerOrderItemsMapper scmCustomerOrderItemsMapper;


    /**
     * 查询客户订单
     * 
     * @param id 客户订单主键
     * @return 客户订单
     */
    @Override
    public ScmCustomerOrders selectScmCustomerOrdersById(Long id)
    {
        return scmCustomerOrdersMapper.selectScmCustomerOrdersById(id);
    }

    /**
     * 查询客户订单列表
     * 
     * @param scmCustomerOrders 客户订单
     * @return 客户订单
     */
    @Override
    public List<ScmCustomerOrders> selectScmCustomerOrdersList(ScmCustomerOrders scmCustomerOrders)
    {
        return scmCustomerOrdersMapper.selectScmCustomerOrdersList(scmCustomerOrders);
    }

    /**
     * 新增客户订单
     * 
     * @param scmCustomerOrders 客户订单
     * @return 结果
     */
    @Transactional
    @Override
    public int insertScmCustomerOrders(ScmCustomerOrders scmCustomerOrders)
    {
        if (scmCustomerOrders == null || scmCustomerOrders.getProjectId() == null || scmCustomerOrders.getProjectId() <= 0){
            return 0;
        }
        ScmProjects project = scmProjectsService.selectScmProjectsByProjectId(scmCustomerOrders.getProjectId());
        if (project == null || project.getCustomerId() == null || project.getCustomerId() <= 0)
            return 0;
        ScmCustomer customer = scmCustomerService.selectScmCustomerById(project.getCustomerId());
        if (customer == null)
            return 0;
        ScmMyCompanyInfo scmMyCompanyInfo = scmMyCompanyInfoService.selectScmMyCompanyInfoList(null).get(0);

        scmCustomerOrders.setOrderCode(scmSequenceParmService.generateScmSequence("cust_order_code"));
        scmCustomerOrders.setOrderDate(DateUtils.getNowDate());
        scmCustomerOrders.setRequestedDeliveryDate(DateUtils.getNowDate());
        scmCustomerOrders.setRepliedDeliveryDate(DateUtils.getNowDate());
        scmCustomerOrders.setTotalAmount(BigDecimal.valueOf(0));
        scmCustomerOrders.setReceivedAmount(BigDecimal.valueOf(0));
        scmCustomerOrders.setPaymentStatus(1L);
        scmCustomerOrders.setCustomerId(customer.getId());
        scmCustomerOrders.setBuyerTitle(customer.getName());
        scmCustomerOrders.setBuyerAddress(customer.getAddress());
        scmCustomerOrders.setBuyerPerson(customer.getLegalPerson());
        scmCustomerOrders.setBuyerPhone(customer.getTelephone());
        scmCustomerOrders.setBuyerAccountBank(customer.getBankName());
        scmCustomerOrders.setBuyerAccountNumber(customer.getBankAccount());
        scmCustomerOrders.setBuyerSignDate(DateUtils.getNowDate());
        scmCustomerOrders.setSellerTitle(scmMyCompanyInfo.getName());
        scmCustomerOrders.setSellerAddress(scmMyCompanyInfo.getAddress());
        scmCustomerOrders.setSellerPerson(scmMyCompanyInfo.getContactName());
        scmCustomerOrders.setSellerPhone(scmMyCompanyInfo.getPhone());
        scmCustomerOrders.setSellerAccountBank(scmMyCompanyInfo.getBankName());
        scmCustomerOrders.setSellerAccountNumber(scmMyCompanyInfo.getBankAccount());
        scmCustomerOrders.setSellerSignDate(DateUtils.getNowDate());
        scmCustomerOrders.setCreateTime(DateUtils.getNowDate());
        int rows = scmCustomerOrdersMapper.insertScmCustomerOrders(scmCustomerOrders);
        insertScmCustomerOrderItems(scmCustomerOrders);
        return rows;
    }

    /**
     * 修改客户订单
     * 
     * @param scmCustomerOrders 客户订单
     * @return 结果
     */
    @Transactional
    @Override
    public int updateScmCustomerOrders(ScmCustomerOrders scmCustomerOrders)
    {
//        ScmCustomerOrders oldCustomerOrders = scmCustomerOrdersMapper.selectScmCustomerOrdersById(scmCustomerOrders.getId());
//        ScmCustomerOrderItems filter = new ScmCustomerOrderItems();
//        filter.setOrderId(scmCustomerOrders.getId());

        BigDecimal totalAmount = BigDecimal.valueOf(0);
        for (ScmCustomerOrderItems item : scmCustomerOrders.getScmCustomerOrderItemsList()){
            if (item.getQuantity().compareTo(BigDecimal.ZERO) > 0){
                item.setAmount(item.getQuantity().multiply(item.getUnitPrice()));
                totalAmount = totalAmount.add(item.getAmount()).add(item.getMoldCost()).add(item.getJigCost());
            }
        }
        scmCustomerOrders.setTotalAmount(totalAmount);
        scmCustomerOrders.setUpdateTime(DateUtils.getNowDate());
        scmCustomerOrdersMapper.deleteScmCustomerOrderItemsByOrderId(scmCustomerOrders.getId());
//        oldCustomerOrders.setScmCustomerOrderItemsList(scmCustomerOrders.getScmCustomerOrderItemsList());
        insertScmCustomerOrderItems(scmCustomerOrders);
        return scmCustomerOrdersMapper.updateScmCustomerOrders(scmCustomerOrders);
    }

    /**
     * 批量删除客户订单
     * 
     * @param ids 需要删除的客户订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteScmCustomerOrdersByIds(Long[] ids)
    {
        scmCustomerOrdersMapper.deleteScmCustomerOrderItemsByOrderIds(ids);
        return scmCustomerOrdersMapper.deleteScmCustomerOrdersByIds(ids);
    }

    /**
     * 删除客户订单信息
     * 
     * @param id 客户订单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteScmCustomerOrdersById(Long id)
    {
        scmCustomerOrdersMapper.deleteScmCustomerOrderItemsByOrderId(id);
        return scmCustomerOrdersMapper.deleteScmCustomerOrdersById(id);
    }

    /**
     * 新增客户订单明细信息
     * 
     * @param scmCustomerOrders 客户订单对象
     */
    public void insertScmCustomerOrderItems(ScmCustomerOrders scmCustomerOrders)
    {
        List<ScmCustomerOrderItems> scmCustomerOrderItemsList = scmCustomerOrders.getScmCustomerOrderItemsList();
        Long id = scmCustomerOrders.getId();
        if (StringUtils.isNotNull(scmCustomerOrderItemsList))
        {
            List<ScmCustomerOrderItems> list = new ArrayList<ScmCustomerOrderItems>();
//            BigDecimal newAmount = BigDecimal.valueOf(0);
//            BigDecimal newIncrementalAmount = BigDecimal.valueOf(0);
            for (ScmCustomerOrderItems scmCustomerOrderItems : scmCustomerOrderItemsList)
            {
                if(scmCustomerOrderItems == null)
                    continue;
                scmCustomerOrderItems.setOrderId(id);
                scmCustomerOrderItems.setOrderCode(scmCustomerOrders.getOrderCode());
//                newAmount = scmCustomerOrderItems.getQuantity().multiply(scmCustomerOrderItems.getUnitPrice());
//                newIncrementalAmount = newIncrementalAmount.add(newAmount).add(scmCustomerOrderItems.getMoldCost() != null ? scmCustomerOrderItems.getMoldCost() : BigDecimal.ZERO)
//                        .add(scmCustomerOrderItems.getJigCost() != null ? scmCustomerOrderItems.getJigCost() : BigDecimal.ZERO);
//                scmCustomerOrderItems.setAmount(newAmount);
                list.add(scmCustomerOrderItems);
            }
            if (list.size() > 0)
            {
                scmCustomerOrdersMapper.batchScmCustomerOrderItems(list);
//                oldCustomerOrders.setTotalAmount(oldCustomerOrders.getTotalAmount().add(newIncrementalAmount));
//                scmCustomerOrdersMapper.updateScmCustomerOrders(oldCustomerOrders);
            }
        }
    }

    /**
     * 初始化客户订单
     *
     * @param projectId 项目id
     * @return 结果
     */
    @Override
    public int initScmCustomerOrders(Long projectId) {
        //根据项目id查询客户报价表 的列表信息
        List<ScmCustomerQuotes> scmCustomerQuotesList = scmCustomerQuotesService.selectScmCustomerQuotesListByProjectId(projectId);
        if (scmCustomerQuotesList == null){
            return 0;
        }

        //清空客当前项目的客户订单表信息
//        ScmCustomerOrders condition = new ScmCustomerOrders();
//        condition.setProjectId(projectId);
//        List<ScmCustomerOrders> scmCustomerOrderslist = scmCustomerOrdersMapper.selectScmCustomerOrdersList(condition);
//        List<Long> ids = new ArrayList<>();
//        if (scmCustomerOrderslist != null && !scmCustomerOrderslist.isEmpty()){
//            for (ScmCustomerOrders item : scmCustomerOrderslist){
//                //获取id并放到数组中
//                ids.add(item.getId());
//            }
//            scmCustomerOrdersMapper.deleteScmCustomerOrdersByIds(ids.toArray(Long[]::new));
//        }

        //遍历查询的结果，组装客户订单信息并插入客户订单表
//        ScmCustomerOrders scmCustomerOrders = new ScmCustomerOrders();;
//        for (ScmCustomerQuotes item : scmCustomerQuotesList){
//            scmCustomerOrders =
//            scmCustomerOrders.setProjectId(projectId);
//            scmCustomerOrders.setQuoteId(item.getId());
//            scmCustomerOrders.setQuoteCode(item.getQuoteCode());
//        }
        return 0;
    }

    @Override
    public ScmCustomerOrders selectScmCustomerOrdersByOrderCode(String orderCode) {
        return scmCustomerOrdersMapper.selectScmCustomerOrdersByOrderCode(orderCode);
    }

    /**
     * 累加金额到订单总金额
     *
     * @param orderId 订单ID
     * @param additionalAmount 新增金额
     * @return 结果
     */
    @Transactional
    @Override
    public int addAmountToTotalAmount(Long orderId, BigDecimal additionalAmount) {
        ScmCustomerOrders order = scmCustomerOrdersMapper.selectScmCustomerOrdersById(orderId);
        if (order != null) {
            BigDecimal newTotalAmount = order.getTotalAmount().add(additionalAmount);
            order.setTotalAmount(newTotalAmount);
            return scmCustomerOrdersMapper.updateScmCustomerOrders(order);
        }
        return 0;
    }

    @Override
    public int selectCustomerOrderCountByMonth(Date yesterday) {
        return scmCustomerOrdersMapper.selectCustomerOrderCountByMonth(yesterday);
    }

    @Override
    public int selectCustomerOrderCountByYear(Date yesterday) {
        return scmCustomerOrdersMapper.selectCustomerOrderCountByYear(yesterday);
    }

    @Override
    public int selectCustomerOrderCountAll() {
        return scmCustomerOrdersMapper.selectCustomerOrderCountAll();
    }

    @Override
    public int selectCustomerOrderCountNotPayed() {
        return scmCustomerOrdersMapper.selectCustomerOrderCountNotPayed();
    }

    @Override
    public int selectCustomerOrderCountExpiring(Date fiveDaysAgo) {
        return scmCustomerOrdersMapper.selectCustomerOrderCountExpiring(fiveDaysAgo);
    }


}
